package com.the4man.framework.service.impl;

import com.the4man.framework.dao.FileMapper;
import com.the4man.framework.model.FileBean;
import com.the4man.framework.pagemodel.PFileBean;
import com.the4man.framework.service.FileServiceI;
import com.the4man.framework.util.DateUtil;
import com.the4man.framework.utils.InitParamUtil;
import com.the4man.framework.utils.RequestUtil;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

/**
 * Created by lenovo on 2017/12/12.
 */
@Service("fileService")
public class FileServiceImpl implements FileServiceI {
    private final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);
    @Autowired
    public FileMapper fileMapper;

    public FileServiceImpl() {
    }

    public List<PFileBean> getAllFileByBuss(String bussId, String bussType) throws Exception {
        PFileBean pFileBean = new PFileBean();
        pFileBean.setBussId(bussId);
        pFileBean.setBussType(bussType);
        List<FileBean> fileList = this.fileMapper.queryFileByBuss(pFileBean);
        List<PFileBean> pfileList = new ArrayList();
        PFileBean file = null;
        Iterator var8 = fileList.iterator();

        while(var8.hasNext()) {
            FileBean b = (FileBean)var8.next();
            file = new PFileBean();
            BeanUtils.copyProperties(b, file);
            pfileList.add(file);
        }

        return pfileList;
    }

    public void insertFile(PFileBean pfileBean) throws Exception {
        String realpath = InitParamUtil.geUploadDirectory();
        String fileBussTypeName = "common";
        int pos = pfileBean.getFiledataFileName().lastIndexOf(".");
        String fileExt = pfileBean.getFiledataFileName().substring(pos + 1);
        realpath = realpath + File.separator + fileBussTypeName;
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
        String ymd = File.separator + DateUtil.getInstance().getYMDTimeStamp() + File.separator;
        realpath = realpath + ymd;
        File uploadDir = new File(realpath);
        System.out.println(uploadDir.getCanonicalFile());
        if(!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        long fileSize = 0L;
        String filePath = File.separator + fileBussTypeName + ymd + newFileName;
        File Filedata = pfileBean.getFiledata();
        String fileName = pfileBean.getFiledataFileName();
        if(Filedata != null) {
            File savefile = new File(new File(realpath), newFileName);
            if(!savefile.getParentFile().exists()) {
                savefile.getParentFile().mkdirs();
            }

            FileUtils.copyFile(Filedata, savefile);
            fileSize = (long)(new FileInputStream(Filedata)).available();
            pfileBean.setFileName(fileName);
            pfileBean.setFilePath(filePath);
            pfileBean.setFileType(fileExt);
            pfileBean.setBussId("11");
            pfileBean.setFileSize(this.formatFileSize(fileSize));
            pfileBean.setFileSizeByte(BigDecimal.valueOf(fileSize));
            pfileBean.setUploadUser(RequestUtil.getSessionUserinfo().getUserid());
            pfileBean.setUploadTime(DateUtil.getInstance().getSqlTimeStamp());
            this.fileMapper.insertFile(pfileBean);
            this.logger.info("file upload, name: " + fileName + " uploadPerson: " + pfileBean.getUploadUser() + " uploadTime: " + pfileBean.getUploadTime() + " fileSize: " + pfileBean.getFileSize() + " filePath: " + filePath);
        } else {
            this.logger.info("upload error! fileName:" + fileName);
        }

    }

    public void downloadFile(PFileBean pfileBean) throws Exception {
        String contextName = InitParamUtil.geUploadDirectory();
        HttpServletResponse response = ServletActionContext.getResponse();
        List<FileBean> flist = this.fileMapper.queryFileByBuss(pfileBean);
        FileBean file = (FileBean)flist.get(0);
        InputStream fis = new BufferedInputStream(new FileInputStream(contextName + file.getFilePath()));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        response.reset();
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getFileName().getBytes("GBK"), "ISO8859_1"));
        response.addHeader("Content-Length", "" + file.getFileSizeByte());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    }

    public String formatFileSize(long fileSize) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeStr = "";
        if(fileSize < 1024L) {
            fileSizeStr = df.format((double)fileSize) + "Byte";
        } else if(fileSize < 1048576L) {
            fileSizeStr = df.format((double)fileSize / 1024.0D) + "K";
        } else if(fileSize < 1073741824L) {
            fileSizeStr = df.format((double)fileSize / 1048576.0D) + "M";
        } else {
            fileSizeStr = df.format((double)fileSize / 1.073741824E9D) + "G";
        }

        return fileSizeStr;
    }

    public void deleteFile(PFileBean pfile) throws Exception {
        List<FileBean> lists = this.fileMapper.queryFileByBuss(pfile);
        if(lists.size() > 0) {
            for(int i = 0; i < lists.size(); ++i) {
                String realpath = InitParamUtil.geUploadDirectory();
                FileBean file = (FileBean)lists.get(i);
                realpath = realpath + file.getFilePath();
                File f = new File(realpath);
                FileUtils.deleteQuietly(f);
            }
        }

        this.fileMapper.deleteFile(pfile);
    }
}
